package com.qf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.dao.mapper.QfOrderDao;
import com.qf.dao.repository.QfOrderRepository;
import com.qf.pojo.dto.QfCourse;
import com.qf.pojo.dto.QfOrder;
import com.qf.pojo.reqVo.PayReq;
import com.qf.pojo.resVo.BaseResult;
import com.qf.service.PayService;
import com.qf.service.UserService;
import com.qf.utils.AlipayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static io.swagger.models.properties.FloatProperty.FORMAT;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    AlipayUtils alipayUtils;
    @Autowired
    UserService userService;
    @Autowired
    QfOrderRepository qfOrderRepository;

    @Autowired
    QfOrderDao qfOrderDao;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private static Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);

    @Override
    public BaseResult pay(PayReq payReq, HttpServletRequest request) {
        //1.验证当前用户的登录状态
        BaseResult userByToken = userService.findUserByToken(request);
        if (userByToken.getCode()==0){
            return userByToken;
        }
        //进行支付逻辑
            //1.使用前端传入的orderid从数据库中查询出该订单的数据
        Optional<QfOrder> byId = qfOrderRepository.findById(payReq.getOrderid());
        if (!byId.isPresent()){
            return new BaseResult(0,"没有该订单的小心！支付失败",null,null);
        }
        QfOrder qfOrder = byId.get();
        //进行订单参数的拼接
        Map map = new HashMap<>();
        //设置订单id
        map.put("out_trade_no",qfOrder.getOrderid());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",qfOrder.getOrderPay().toString());

        map.put("subject","课程购买！");
        //使用orderid查询出购买的课程信息
        List<QfCourse> courseList =  qfOrderDao.findCourseByOrderId(payReq.getOrderid());
        //循环拼接 课程名称
        StringBuffer stringBuffer = new StringBuffer();
        for (QfCourse qf: courseList
             ) {
            stringBuffer.append(qf.getCourseName()+",");
        }
        map.put("body",stringBuffer.toString());
        //将Map集合转为json串
        String parmas = JSONObject.toJSONString(map);
        try {
            String form = alipayUtils.alipayClient(parmas);


            //将该条支付信息发送到延迟队列中，并且设置1分钟的超时时间，如果超时，则将数据库修改为取消支付
            rabbitTemplate.convertAndSend("dead-pay-topic-exchange", "pay", qfOrder.getOrderid(), new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    MessageProperties messageProperties = message.getMessageProperties();
                    //毫秒存储
                    messageProperties.setExpiration("30000");
                    return message;
                }
            });

            //将数据库的订单状态修改为正在支付
            qfOrder.setOrderStatus(3);
            qfOrderRepository.saveAndFlush(qfOrder);
            return new BaseResult(1,"请求支付成功！",form,null);
        }catch (Exception e){
            return new BaseResult(0,"请求支付失败！",null,null);
        }
    }

    @Override
    public void returnUrl(HttpServletRequest request) {
        //进行验签，判断是否时支付宝发给我我们的请求
        boolean b = alipayUtils.notifyUrl(request);
        Map<String, String> map = AlipayUtils.convertRequestParamsToMap(request);
        //当前订单的id
        String out_trade_no = map.get("out_trade_no");
        Optional<QfOrder> byId = qfOrderRepository.findById(out_trade_no);
        //使用订单id查询出订单的金额 与支付宝回调中的金额进行比对，如果比对成功，则修改状态为 2 支付成功，如果比对失败则修改为 5 支付失败！
        if (!b){
            logger.debug("验签失败！");
            byId.get().setOrderStatus(5);
            return;
        }else {
            logger.debug("验签成功！");
            //验签成功 我们需要 比对金额参数
            String total_amount = map.get("total_amount");
            QfOrder qfOrder = byId.get();
            //价格比对
            if ((qfOrder.getOrderPay().compareTo(Double.valueOf(total_amount)))!=0){
                logger.debug("金额匹配不通过");
                byId.get().setOrderStatus(5);
            }else{
                byId.get().setOrderStatus(2);
            }
        }
        //修改数据库的订单状态
        qfOrderRepository.saveAndFlush(byId.get());


    }
}
